// miniprogram/pages/login/index.js
import * as R from 'ramda';
import { Either, IO } from '../../utils/vendor/ramda-fantasy';
import U from '../../utils/index';
import WxValidate from '../../utils/vendor/WxValidate.js';
const globalData = getApp().globalData;
const validator = {
  rules: {
    username: {
      required: true,
    },
    password: {
      required: true,
    },
  },
  messages: {
    username: {
      required: '请输入用户名',
    },
    password: {
      required: '请输入密码',
    },
  }
};
const wxValidate = new WxValidate(validator.rules, validator.messages);

const validateAuthorize = R.ifElse(
  R.isNil,
  () => Either.Left('必须微信授权才能登录系统'),
  Either.Right
);

const handleAuthorizeAfter = userInfo => IO(
  R.compose(
    v => wx.setStorageSync('userInfo', v),
    () => globalData.userInfo = userInfo
  )
);

const handleRequestLogin = data => U.handleRequest({}, () => U.reqPost({
  url:'/user/login',
  data
}));

const handleLoginRes = res => IO(
  R.compose(
    () => wx.reLaunch({ url: '/pages/wait/index' }),
    () => wx.setStorageSync('token', globalData.token),
    () => globalData.token = res.data.token,
    () => wx.setStorageSync('userInfo', globalData.userInfo),
    () => globalData.userInfo.realname = res.data.result_user.realname,
    () => globalData.userInfo.userId = res.data.result_user.user_id,
    () => globalData.userInfo.role = res.data.result_user.role
  )
);

Page({
  /**
   * 页面的初始数据
   */
  data: {
    form: {
      username: null,
      password: null
    }
  },
  
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },
  
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },
  setFormData(e) {
    U.setFormData(e).run(this);
  },
  onClickLogin(e) {
    /*U.wxP(wx.login).then(res => {
      if(res.code) {
        console.log('成功')
      }
    })*/
    R.compose(
      U.runIO,
      U.handleError,
      // 登录请求
      R.map(
        R.compose(
          U.fork,
          R.map(R.compose(U.runIO, handleLoginRes)),
          handleRequestLogin
        )
      ),
      // 清除空格验证数据
      R.chain(U.validate(wxValidate)),
      R.map(
        R.compose(
          R.tap(form => this.setData({ form })),
          R.map(U.trim),
          R.always(this.data.form)
        )
      ),
      // 微信授权后处理
      R.map(
        R.compose(
          U.runIO,
          handleAuthorizeAfter
        )
      ),
      validateAuthorize
    )(e.detail.userInfo);
  },
  callPhone() {
    wx.makePhoneCall({ phoneNumber: '15066566163' })
  }
})
